package com.guan.study.easyExcelDemo.read.read02_合并单元格读取;

import com.alibaba.excel.EasyExcel;
import com.guan.study.easyExcelDemo.Teacher;
import com.guan.study.easyExcelDemo.read.ReadLisitener;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @Date: 2023/7/2 10:16
 * @Author: yaobai
 * @Description: 读取带有合并行的excel表格，根据 read 读取到的结果，发现规律：
 * 当读取到合并行单元格时，数据是属于合并行的首行。例如：第3-5行合并，内容为“AA”,
 * 则“AA”会被当作第3行的数据读取，第4-5行为空。
 */
@RequestMapping("/readExcel02")
@RestController
@Log4j2
public class ReadExcel02 {

    @PostMapping("/import/teacher")
    public void importUserExcel(@RequestBody MultipartFile file) {
        try {
            ReadLisitener<Teacher> lisitener2 = new ReadLisitener<>();
            EasyExcel.read(file.getInputStream(), Teacher.class, lisitener2)
                   .sheet("新入职教师统计表")
                   .doRead();
            List<Teacher> list = lisitener2.getList();
            list.stream().forEach(v -> System.out.println(v));
            log.info("\n++++++ 整理数据 +++++++++");
            //临时名称，记录当前对象的学院名，当下一个对象该字段为空是，则获取改临时名称
            String tempname = "";
            for (int i = 0; i < list.size(); i++) {
                Teacher t = list.get(i);
                String name = t.getSchool();
                if (StringUtils.isNotBlank(name)){
                    tempname = name;
                }else {
                    t.setSchool(tempname);
                }
            }

            list.stream().forEach(v -> System.out.println(v));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
